<template>
    <div class="show-contain"
         :class="[compOption.isClick && mode == 'sheji' ? 'active-bordert' : '',mode == 'sheji' ? 'widget-item' : '']"
         @click.stop="clickToggleBg">
        <div style="display: flex;align-items: center;width: 100%;margin-bottom: 10px">
            <div class="required-title" v-if="mode != 'sheji' && compOption.options.required">*</div>
            <div class="sort-style" v-if="prentCompOption.isChildSort && prentCompOption.isPrentAndChildSort">
                {{ prentCompOption.sortTitle + '.' + (childInd + 1) }}
            </div>
            <div class="sort-style" v-else-if="prentCompOption.isChildSort">{{ childInd + 1 }}</div>
            <div class="sort-style" v-else-if="prentCompOption.isPrentAndChildSort">{{ prentCompOption.sortTitle }}
            </div>
            <div class="title-openEdit" @click.stop="openTitleEditor(compOption.displayName)"
                 v-html="mode == 'sheji' ? compOption.displayName : compOption.displayName + ((!compOption.options.hasOwnProperty('totalSource') || compOption.options.totalSource == 0) ? '' :  ` <span style='width:80px;align-self: flex-end'>(${compOption.options.totalSource}) 分</span>`)"
                 :style="{border:mode == 'sheji' ? '1px solid rgba(204, 200, 200, 0.5)' : 'none',padding:mode == 'sheji' ? '10px' : '0',
           }" style="font-size: 18px"></div>
            <div style="margin-left: 10px" v-if="compOption.isClick && mode == 'sheji'">
                <div class="flex-row">
                    <!--                    <span class="el-icon-rank font-color-main" style="margin-right: 10px"></span>-->
                    <!--                    <span class="el-icon-document-copy font-color-main" style="margin-right: 10px"></span>-->
                    <span class="el-icon-delete font-color-main" @click="delSourceZu"></span>
                </div>
            </div>
        </div>
        <div  style="margin-bottom: 10px;width: 100%" v-if="mode == 'yulan' && (compOption.options.score !==null && compOption.options.score != '不适用')">
            <el-row style="display: flex;align-items: center">
                <el-col :span="1">
                    <div>已得</div>
                </el-col>
                <el-col :span="3">
                    <el-input v-model="compOption.options.score"  class="el-border-dev"
                              :disabled="sourceMode == 'yulan'"></el-input>
                </el-col>
                <el-col :span="2">
                    <div>分</div>
                </el-col>
            </el-row>
        </div>
        <div v-if="compOption.options.questionStem" :style="{marginBottom: mode == 'sheji' ? '10px' : '20px'}"
             style="width: 100%">
            <el-input v-model="compOption.options.placeholderContent" v-if="mode == 'sheji'"
                      placeholder="请输入题干说明"
                      style="width: 100%"></el-input>
            <div v-else class="tigan">
                {{ compOption.options.placeholderContent }}
            </div>
        </div>

        <template v-if="(!compOption.options.value.name) && (!compOption.options.value.url)">
            <el-upload
                    class="upload-demo"
                    action="http://129.211.212.235:8095/file/upload"
                    :limit="1"
                    :show-file-list="false"
                    :before-upload="beforeUploadAudio"
                    :on-success="successFile"
                    :on-error="errorFile"
            >
                <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
        </template>
        <template v-else>
            <div style="width: 100%;display: flex;align-items: center">
                <AudioPlayerWithMarkers :audio-url="compOption.options.value.url"
                                        @throwMarks="getMarks" @deleteMarks="delMark"
                                        @blurMark="getBlurMarks" ref="refAudio"
                :mode="mode" @durationChange="handleDurationChange" ></AudioPlayerWithMarkers>
                <div style="color: #ec2d2d;cursor: pointer"
                     v-if="mode != 'yulan'"
                @click="delLuyin"><i class="el-icon-delete-solid" style="margin-right: 5px"
                ></i>删除录音</div>
                <el-time-picker
                    v-model="selectedTime"
                    value-format="HH:mm:ss"
                    placeholder="选择秒数"
                    :append-to-body="false"
                    style="margin: 0 10px; width: 120px"
                    @change="handleTimeJump"
                ></el-time-picker>
            </div>
        </template>

        <div v-if="mode != 'sheji'" style="margin-top: 10px;width: 100%">
            <render-remark :comp-option="compOption" :mode="mode"></render-remark>
        </div>
        <dialog-editor ref="dialogEditor" @throwHtml="(html) => compOption.displayName = html"></dialog-editor>
    </div>
</template>

<script>
import {openEditor} from '@/minexs/index'
import {methodRef} from '@/components/form-designer/widget-panel/main-comp-panal/methodRef'
import RenderRemark from "@/components/renderRemark/renderRemark.vue";
import AudioPlayerWithMarkers from "@/components/AudioPlayerWithMarkers/AudioPlayerWithMarkers.vue";

export default {
    name: "luyin-editor",
    components: {RenderRemark, AudioPlayerWithMarkers},
    mixins: [openEditor, methodRef],
    props: {
        compOption: {
            type: Object,
        },
        prentCompOption: {
            type: Object,
        },
        childInd: {
            type: Number
        },
        mode: {
            type: String,
            default: 'sheji'
            /**
             * sheji
             * xiezuo
             * yulan
             * */
        },
        sourceMode: {
            type: String,
            default: 'yulan'
        },
        proviceList: {
            type: Array
        }
    },
    mounted() {
        if (this.compOption.options.value.name && this.compOption.options.value.url) {
            this.$nextTick(() => {
                this.$refs.refAudio.setMarks(this.compOption.options.markers)
            })
        }
    },
    data() {
        return {
            acceptTypes: '.mp3,.wav,.flac,.aac',
            // 音频格式正则表达式
            audioRegExp: /\.(mp3|wav|flac|aac|m4a)$/i,
            selectedTime: null,       // 绑定时间选择器
            audioDuration: 0,         // 存储音频总时长（秒）
            timePickerOptions: {      // 时间选择器配置
                selectableRange: '00:00:00 - 00:00:00' // 初始值，会动态更新
            }
        }
    },
    methods: {
        clickToggleBg() {
            if (this.$props.mode == 'sheji') this.$emit('changeClick', this.$props.compOption.id, this.$props.prentCompOption.id)
        },
        changeValue() {
            if (this.compOption.options.onChangeValue) {
                this.$emit('activeStartChange', {
                    code: this.compOption.options.onChangeValue,
                    value: this.compOption.options.value
                })
            }
        },
        delSourceZu() {
            this.$confirm('是否确认删除当前问题', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ind = this.prentCompOption.widgetList.findIndex(item => item.id == this.compOption.id)
                if (ind != -1) {
                    this.prentCompOption.widgetList.splice(ind, 1)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }
            })
        },
        getBlurMarks(mark, ind) {
            this.compOption.options.markers.splice(ind, 1, {
                ...mark
            })
        },
        delMark(ind) {
            this.compOption.options.markers.splice(ind, 1)
        },
        getMarks(obj) {
            this.compOption.options.markers.push({
                ...obj
            })
        },
        beforeUploadAudio(file) {
            if (!this.audioRegExp.test(file.name)) {
                this.$message.error('请上传 MP3、WAV、FLAC 或 AAC 格式的音频文件！');
                return false;
            }
            this.compOption.options.value.name = file.name
            return true
        },
        successFile(res) {
            if (res.code == 200) {
                this.$message.success('上传成功')
                this.compOption.options.value.url = res.data
            } else {
                this.$message.error(res.msg || '上传失败')
            }
        },
        errorFile(err) {
            this.compOption.options.value.name = ''
            this.compOption.options.value.url = ''
            this.$message.error(err || '上传失败')
        },
        delLuyin(){
            this.$confirm('是否确认要删除此录音', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$refs.refAudio.setMarks([])
                this.compOption.options.value.name = ''
                this.compOption.options.value.url = ''
                this.compOption.options.markers = []

            })
        },
        // 新增：处理音频时长变化
        handleDurationChange(duration) {
            this.audioDuration = Math.floor(duration);
            // 将总秒数转换为HH:mm:ss格式，用于设置时间选择范围
            const maxTime = this.formatSecondsToTime(this.audioDuration);
            this.timePickerOptions.selectableRange = `00:00:00 - ${maxTime}`;
        },
        // 处理时间跳转
        handleTimeJump() {
            if (!this.selectedTime) {
                this.$message.warning('请选择时间点');
                return;
            }
            // 将HH:mm:ss格式转换为总秒数
            const totalSeconds = this.parseTimeToSeconds(this.selectedTime);
            // 调用音频组件的跳转方法
            if (this.$refs.refAudio && this.$refs.refAudio.seek) {
                this.$refs.refAudio.seek(totalSeconds);
            }
        },
        // 辅助方法：将秒数转换为HH:mm:ss格式
        formatSecondsToTime(seconds) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;

            // 补零操作，确保格式统一
            return [
                hours.toString().padStart(2, '0'),
                minutes.toString().padStart(2, '0'),
                secs.toString().padStart(2, '0')
            ].join(':');
        },

        // 辅助方法：将HH:mm:ss格式转换为总秒数
        parseTimeToSeconds(timeStr) {
            const [hours, minutes, seconds] = timeStr.split(':').map(Number);
            return hours * 3600 + minutes * 60 + seconds;
        },

    }
}
</script>

<style scoped>
.widget-item {
    border: .5px solid #e5e5e5;
    border-radius: 3px;
    padding: 20px;
}
</style>
